/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package views;

import entities.Usuarios;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.*;
import java.util.Enumeration;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.filechooser.FileNameExtensionFilter;
import logica.LogicaBackUp;

/**
 *
 * @author Smuggler
 */
public class OpcionesAvanzadas extends javax.swing.JFrame {
    public static JFrame frame;
    private Usuarios usuario;
    private FileWriter fichero = null;
    private Properties prop;
    private InputStream is;
    private OutputStream os;
    JFileChooser chooser;
    String txtNombre = "";
    public static String rutaPropertiesFile = "Configuraciones.properties";
    private ConfigServer configServer;

    /**
     * Creates new form OpcionesAvanzadas
     */
    public OpcionesAvanzadas(Usuarios usuario) {
        initComponents();
        this.usuario = usuario;
    }

    public JFrame getFrame() {
        return frame;
    }

    /**
     *
     * @param object: Es el objeto que queremos saber si está creado
     * (instanciado)
     * @return true: Si el objeto esta creado false: Caso contrario
     */
    public static boolean frameCreado(Object object) {
        if (object == null) {
            return false;
        } else {
            return true;
        }
    }

    /**
     *
     * @param object: Es el objeto que queremos saber si está cerrado
     * @return true: Si el frame está cerrado false: Caso contrario
     */
    public static boolean frameCerrado(Object object) {
        if (object == null) {
            return true;
        } else {
            return false;
        }
    }

    /**
     *
     * @param frame: El frame que queremos saber si está visible
     * @return true: Si el frame está visible false: Si no está visible
     */
    public static boolean frameVisible(JFrame frame) {
        if (frame.isVisible()) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 
     * @param frame: El frame que queremos se "rearme" (redibuje)
     */
    public static void rearmarFrame(JFrame frame) {
        frame.setVisible(true);
        frame.pack();
        frame.repaint();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        panel1 = new java.awt.Panel();
        backupButton = new javax.swing.JButton();
        restaurarButton = new javax.swing.JButton();
        datosDelSistemaLabel = new javax.swing.JLabel();
        panel2 = new java.awt.Panel();
        checkInButton = new javax.swing.JButton();
        contratoButton = new javax.swing.JButton();
        configServerButton = new javax.swing.JButton();
        documentosLabel = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        panel1.setBackground(new java.awt.Color(153, 153, 153));

        backupButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/BackUP.png"))); // NOI18N
        backupButton.setText("Hacer Backup");
        backupButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                backupButtonActionPerformed(evt);
            }
        });

        restaurarButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/Restaurar.png"))); // NOI18N
        restaurarButton.setText("Restaurar");
        restaurarButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                restaurarButtonActionPerformed(evt);
            }
        });

        datosDelSistemaLabel.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
        datosDelSistemaLabel.setForeground(new java.awt.Color(255, 255, 255));
        datosDelSistemaLabel.setText("Datos del Sistema");

        javax.swing.GroupLayout panel1Layout = new javax.swing.GroupLayout(panel1);
        panel1.setLayout(panel1Layout);
        panel1Layout.setHorizontalGroup(
            panel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(panel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(backupButton)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 66, Short.MAX_VALUE)
                .addComponent(restaurarButton, javax.swing.GroupLayout.PREFERRED_SIZE, 134, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, panel1Layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(datosDelSistemaLabel)
                .addGap(114, 114, 114))
        );
        panel1Layout.setVerticalGroup(
            panel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(panel1Layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(datosDelSistemaLabel)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(panel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(backupButton)
                    .addComponent(restaurarButton))
                .addContainerGap())
        );

        panel2.setBackground(new java.awt.Color(153, 153, 153));

        checkInButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/checkin.png"))); // NOI18N
        checkInButton.setText("Check-In");
        checkInButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                checkInButtonActionPerformed(evt);
            }
        });

        contratoButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/contrato.png"))); // NOI18N
        contratoButton.setText("Contrato");
        contratoButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                contratoButtonActionPerformed(evt);
            }
        });

        configServerButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/config.png"))); // NOI18N
        configServerButton.setText("Configurar Servidor");
        configServerButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                configServerButtonActionPerformed(evt);
            }
        });

        documentosLabel.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
        documentosLabel.setForeground(new java.awt.Color(255, 255, 255));
        documentosLabel.setText("Documentos (plantillas)");

        javax.swing.GroupLayout panel2Layout = new javax.swing.GroupLayout(panel2);
        panel2.setLayout(panel2Layout);
        panel2Layout.setHorizontalGroup(
            panel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(panel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(panel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(panel2Layout.createSequentialGroup()
                        .addComponent(checkInButton, javax.swing.GroupLayout.PREFERRED_SIZE, 119, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 95, Short.MAX_VALUE)
                        .addComponent(contratoButton, javax.swing.GroupLayout.PREFERRED_SIZE, 119, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addContainerGap())
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, panel2Layout.createSequentialGroup()
                        .addGap(0, 0, Short.MAX_VALUE)
                        .addComponent(configServerButton)
                        .addGap(91, 91, 91))))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, panel2Layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(documentosLabel)
                .addGap(89, 89, 89))
        );
        panel2Layout.setVerticalGroup(
            panel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(panel2Layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(documentosLabel)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(panel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(checkInButton)
                    .addComponent(contratoButton))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(configServerButton)
                .addContainerGap())
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                    .addComponent(panel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(panel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(38, 38, 38)
                .addComponent(panel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 38, Short.MAX_VALUE)
                .addComponent(panel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(31, 31, 31))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void restaurarButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_restaurarButtonActionPerformed
        try {
            new LogicaBackUp().restartBackUp();
        } catch (IOException ex) {
            Logger.getLogger(OpcionesAvanzadas.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_restaurarButtonActionPerformed

    private void backupButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_backupButtonActionPerformed
        new LogicaBackUp().crearBackup();        // TODO add your handling code here:

    }//GEN-LAST:event_backupButtonActionPerformed

    public static void seleccionarPlantillaCheckIn() {
        checkInButton.doClick();
    }

    public static void seleccionarConfigServer() {
        configServerButton.doClick();
    }

    public static void seleccionarPlantillaContrato() {
        contratoButton.doClick();
    }

    private void checkInButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_checkInButtonActionPerformed
        int respuesta = 0;
        chooser = new JFileChooser();
        prop = new Properties();
        is = null;
        os = null;
        String keyNueva = "checkIn";

        try {
            is = new FileInputStream(rutaPropertiesFile);
            //os = new FileOutputStream(rutaPropertiesFile);
        } catch (IOException e) {
            System.out.println(e.toString());
        }


        //Recorrido de propiedades sin conocer su nombre
        /*
         * for (Enumeration e = prop.keys(); e.hasMoreElements() ; ) { //
         * Obtenemos el objeto Object obj = e.nextElement();
         * System.out.println(obj + ": " + prop.getProperty(obj.toString())); }
         */

        chooser.setDialogTitle("Selección de plantilla para Check-In");
        chooser.setCurrentDirectory(new java.io.File("."));
        chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
        chooser.setAcceptAllFileFilterUsed(false);
        FileNameExtensionFilter filter = new FileNameExtensionFilter("Texto Plano", "txt");
        chooser.setFileFilter(filter);
        if ((respuesta = chooser.showSaveDialog(chooser)) == JFileChooser.APPROVE_OPTION) {
            //txtNombre tiene la ruta completa del archivo seleccionado
            txtNombre = chooser.getSelectedFile().toString();

            //TODO hacer que la ruta de este archivo se guarde en un archivo de propiedades
        }
        //respuesta = 0 cuando se elige un archivo, esto es para evitar que se guarde el archivo con errores
        if (respuesta == 0) {
            try {
                /*
                 * prop.load(is); String anterior = (String)
                 * prop.setProperty("checkIn", txtNombre);
                 * System.out.println("anterior: "+anterior); prop.store(os,
                 * "nuevo doc checkIn"); JOptionPane.showMessageDialog(null,
                 * "Cambios guardados correctamente");
                 */

                prop.load(is);
                is.close();
                Properties newProps = new Properties();
                Enumeration enumProps = prop.propertyNames();
                String key = "";
                if (!enumProps.hasMoreElements()) {
                    newProps.setProperty(keyNueva, txtNombre);
                }
                while (enumProps.hasMoreElements()) {
                    key = (String) enumProps.nextElement();
                    if (key.equals(keyNueva)) {
                        newProps.setProperty(keyNueva, txtNombre);
                    } else {
                        newProps.setProperty(key, prop.getProperty(key));
                        if (!enumProps.hasMoreElements()) {
                            newProps.setProperty(keyNueva, txtNombre);
                        }
                    }
                }
                os = new FileOutputStream(rutaPropertiesFile);
                newProps.store(os, "Properties File de SIAAT");
                os.close();
                JOptionPane.showMessageDialog(null, "Cambios guardados correctamente");
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }//GEN-LAST:event_checkInButtonActionPerformed

    private void contratoButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_contratoButtonActionPerformed
        chooser = new JFileChooser();
        prop = new Properties();
        is = null;
        os = null;
        int respuesta = 0;
        String keyNueva = "contrato";

        try {
            is = new FileInputStream(rutaPropertiesFile);
            os = new FileOutputStream(rutaPropertiesFile, true);
        } catch (IOException e) {
            System.out.println(e.toString());
        }
        chooser.setDialogTitle("Selección de plantilla para Contrato");
        chooser.setCurrentDirectory(new java.io.File("."));
        chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
        chooser.setAcceptAllFileFilterUsed(false);
        FileNameExtensionFilter filter = new FileNameExtensionFilter("Texto Plano", "txt");
        chooser.setFileFilter(filter);
        if ((respuesta = chooser.showSaveDialog(chooser)) == JFileChooser.APPROVE_OPTION) {
            //txtNombre tiene la ruta completa del archivo seleccionado
            txtNombre = chooser.getSelectedFile().toString();

            //TODO hacer que la ruta de este archivo se guarde en un archivo de propiedades
        }
        //respuesta = 0 cuando se elige un archivo, esto es para evitar que se guarde el archivo con errores
        if (respuesta == 0) {
            try {

                /*
                 * prop.load(is); String anterior = (String)
                 * prop.setProperty("checkIn", txtNombre);
                 * System.out.println("anterior: "+anterior); prop.store(os,
                 * "nuevo doc checkIn"); JOptionPane.showMessageDialog(null,
                 * "Cambios guardados correctamente");
                 */

                prop.load(is);
                is.close();
                Properties newProps = new Properties();
                Enumeration enumProps = prop.propertyNames();
                String key = "";
                if (!enumProps.hasMoreElements()) {
                    newProps.setProperty(keyNueva, txtNombre);
                }
                while (enumProps.hasMoreElements()) {
                    key = (String) enumProps.nextElement();
                    if (key.equals(keyNueva)) {
                        newProps.setProperty(key, txtNombre);
                    } else {
                        newProps.setProperty(key, prop.getProperty(key));
                        if (!enumProps.hasMoreElements()) {
                            newProps.setProperty(keyNueva, txtNombre);
                        }
                    }
                }
                os = new FileOutputStream(rutaPropertiesFile);
                newProps.store(os, "Properties File de SIAAT");
                os.close();

                JOptionPane.showMessageDialog(null, "Cambios guardados correctamente");
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }//GEN-LAST:event_contratoButtonActionPerformed

    private void configServerButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_configServerButtonActionPerformed
        //ConfigServer.main();
        if ((frameCreado(configServer)) && (frameCerrado(configServer.getFrame()))) {
            configServer = null;
        }
        if (!frameCreado(configServer)) {
            configServer = new ConfigServer(usuario);
            configServer.main(usuario);
        } else {
            if (!frameVisible(configServer.getFrame())) {
                rearmarFrame(configServer.getFrame());
            }
            configServer.getFrame().toFront();
        }
    }//GEN-LAST:event_configServerButtonActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(Usuarios usuario) {
        final Usuarios usuarioActual = usuario;
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /*
         * If Nimbus (introduced in Java SE 6) is not available, stay with the
         * default look and feel. For details see
         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(OpcionesAvanzadas.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(OpcionesAvanzadas.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(OpcionesAvanzadas.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(OpcionesAvanzadas.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /*
         * Create and display the form
         */
        OpcionesAvanzadas.frame = new OpcionesAvanzadas(usuarioActual);
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                //frame = new JFrame();
                frame.setTitle("Opciones Avanzadas - SIAAT");
                //frame.setContentPane();
                frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
                frame.pack();
                //frame.setIconImage(new ImageIcon(getClass().getResource("/images/logo.png")).getImage());
                frame.setVisible(true);
                frame.addWindowListener(new WindowAdapter() {
                    public void windowClosing(WindowEvent e) {
                      if (frame != null) {
                            frame.setVisible(false);
                        }
                        frame = null;
                    }
                });
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton backupButton;
    private static javax.swing.JButton checkInButton;
    private static javax.swing.JButton configServerButton;
    private static javax.swing.JButton contratoButton;
    private javax.swing.JLabel datosDelSistemaLabel;
    private javax.swing.JLabel documentosLabel;
    private java.awt.Panel panel1;
    private java.awt.Panel panel2;
    private javax.swing.JButton restaurarButton;
    // End of variables declaration//GEN-END:variables
}
